#include <cctype>
#include <cstdio>
#include <iostream>
#include <algorithm>

using ll = long long;

struct CinLL{
    char c;
    ll n,w;
    CinLL&operator>>(ll &ref)noexcept{
        c=0,n=0,w=1;
        while(!isdigit(c)){
            if(c=='-')w=-1;
            c=getchar();
        }
        while(isdigit(c)){
            n=n*10+c-'0';
            c=getchar();
        }
        ref = n*w;
        return *this;
    }
}cin_ll;

auto &is = cin_ll;
auto &os = std::cout;

const ll max_n = 1e6+5;
ll n, ans{1};
ll weight[max_n],l_son[max_n],r_son[max_n];

ll dfs(const ll a,const ll b,const ll sum)noexcept{
    if(a==-1&&b==-1){
        return 0;
    }else if((a==-1||b==-1)&&a!=b){
        return -1;
    }
    if(weight[a]!=weight[b]){
        return -1;
    }
    const ll ret_a {dfs(l_son[a],r_son[b],2)}, ret_b{dfs(r_son[a], l_son[b],2)};
    if(ret_a==-1||ret_b==-1){
        return -1;
    }else{
        return ret_a+ret_b+sum;
    }
}

int main(){
    is>>n;
    for(ll i{1};i<=n;i++){
        is>>weight[i];
    }
    for(ll i{1};i<=n;i++){
        is>>l_son[i]>>r_son[i];
    }
    for(ll i{1};i<=n;i++){
        if(const auto tmp = dfs(l_son[i],r_son[i],3);tmp!=-1){
            ans = std::max(ans,tmp);
        }
    }
    os<<ans<<'\n';
}